# -*- coding: utf-8 -*-
from gevent.pywsgi import WSGIServer
import ac_match_online
import ac_match_online_quchong
import ac_match_online_cg
import ac_match_online_annex
# import ac_match_online_cs
import json
import sys
import time
import datetime
import parse
from flask import Flask,request,jsonify,render_template,session,redirect
from flask_restful import Api, abort, Resource
from ExtractIndustry import getIndustry
from ExtractAddress import partitionByName
from toShort import compNameToShort
from myConfig.ConfigCenterHandler import *

from concurrent.futures import ThreadPoolExecutor
import market_main
import market_single_notice
import market_single_project
import market_batch_project
import logging
#word与pdf解析
import pdf_filepath

today = datetime.datetime.now().strftime('%Y%m%d')
logger = logging.getLogger('single_project')
logger.setLevel(logging.INFO)
fh = logging.FileHandler(filename='/home/analysis-project/market_log/single_project_'+today+'.log', encoding='utf-8')
formatter = logging.Formatter('%(asctime)s -- %(name)s -- %(levelname)s \n%(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)

valid_data = {
    'appkey': 'aae9b67e95d94bf4b1f4a627e5ec417e'
}
error_key_message = {
    'code': 1001,'message':'服务超时'
}
ac = ac_match_online.Ac_match()
ac_quchong = ac_match_online_quchong.Ac_match()
ac_cg = ac_match_online_cg.Ac_match()
ac_annex = ac_match_online_annex.Ac_match()
# ac_cs = ac_match_online_cs.Ac_match()

executor_duplicate = ThreadPoolExecutor(1)
executor_label = ThreadPoolExecutor(1)
executor_single = ThreadPoolExecutor(1)
executor_analysis = ThreadPoolExecutor(1)
executor_duplicate_project = ThreadPoolExecutor(1)

app = Flask(__name__)

@app.route('/knowledge_section_push',methods=['POST'])
def knowledge_section_push():
  data = request.get_data()
  # print(request.values)
  # print(type(data))
  # print(data)
  final = ac.get_main_item(data)

  f_str = str(final)
  # print(f_str)
  # h = "helloworld"
  return f_str

@app.route('/knowledge_section_annex',methods=['POST'])
def knowledge_section_annex():
  data = request.get_data()
  # print(request.values)
  # print(type(data))
  # print(data)
  final = ac_annex.get_main_item(data)

  f_str = str(final)
  # print(f_str)
  # h = "helloworld"
  return f_str

@app.route('/knowledge_section_cg_test',methods=['POST'])
def knowledge_section_push_cg():
  data = request.get_data()
  # print(request.values)
  # print(type(data))
  # print(data)
  final = ac_cg.get_main_item(data)

  f_str = str(final)
  # print(f_str)
  # h = "helloworld"
  return f_str


@app.route('/knowledge_section_push_qc',methods=['POST'])
def knowledge_section_push_qc():
  data = request.get_data()
  # print(request.values)
  # print(type(data))
  # print(data)
  executor_analysis.submit(ac_quchong.get_main_item, data)
  f_str = "解析完成"
#  final = ac.get_main_item(data)
#  
#  f_str = str(final)
  # print(f_str)
  # h = "helloworld"
  return f_str

# @app.route('/test',methods=['POST'])
# def knowledge_section_push_cs():
#   data = request.get_data()
#   final = ac_cs.get_main_item(data)
#   f_str = str(final)
#   return f_str

@app.route('/address',methods=['POST'])
def address():
  appkey = valid_data['appkey']
  data = request.get_data(as_text=True)
  # data = json.dumps(data).replace("  ", "").replace("\\n", "").replace('"', '').replace("'", '"')
  paramAppkey = json.loads(data)['appkey']
  paramName = json.loads(data)['name'].replace("  ", "").replace("\\n", "").replace('"', '').replace("'", '"')
  paramAddr = ""
  try:
    paramAddr = json.loads(data)['addr']
  except:
      pass
  if paramAppkey != appkey:
    return error_key_message
  
  return str(partitionByName(paramName,paramAddr))

@app.route('/industry',methods=['POST'])
def industry():
  appkey = valid_data['appkey']
  data = request.get_data(as_text=True)
  paramAppkey = json.loads(data)['appkey']
  paramName = json.loads(data)['name'].replace("  ", "").replace("\\n", "").replace('"', '').replace("'", '"')
  # print(paramName)
  if paramAppkey != appkey:
    return error_key_message

  return str(getIndustry(paramName))

@app.route('/toshort',methods=['POST'])
def toshort():
  data = request.get_data(as_text=True)
  compName = json.loads(data)['compName']
  
  return compNameToShort(compName)

# 地域接口验证页面
@app.route('/addr', methods = ['GET'])
def viewVerifyAddress():
    # if session.get("loginFlag") != "success":
    #     return redirect('login')
    # else:
    #     session['appkey'] = valid_data.get('appkey')
    #     result_session = session
    #     return render_template('verifyAddressApi.html', result_session = result_session)
    return render_template('verifyAddressApi.html', appKey=valid_data.get('appkey'))

# 配置中心页面
@app.route('/configCenter', methods = ['GET'])
def viewConfigCenter():
    return render_template('/configCenter/search.html')

# 查询配置文件的数据
@app.route('/configCenter/list', methods = ['GET'])
def searchConfigCenterList():
    return json.dumps(loadAuthKeysList())

# 配置中心编辑页面
@app.route('/configCenter/edit', methods = ['GET'])
def viewConfigCenterEdit():
    return render_template('/configCenter/edit.html')

# 操作配置中心文件的数据，进行热更新
@app.route('/api/submitConfigCenterData', methods = ['POST'])
def submitConfigCenter():
    data = request.get_data(as_text=True)
    return json.dumps(configCenterSubmit(json.loads(data)))

'''
查重打标
'''
@app.route('/single_check_project',methods=['POST'])
def single_check_project():
    data = request.get_data()
    parameter = json.loads(data)
    result = market_single_project.duplicate_single_only_main(parameter[0],parameter[1],parameter[2],parameter[3])
#    time_now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
#    print('Check Sucessful in [{0}]'.format(time_now))
    logger.info('输入数据：{0}\n输出结果：{1}'.format(parameter[0],result))
    return str(result)

@app.route('/duplicate_batch_project',methods=['POST'])
def duplicate_batch_project():
    data = request.get_data()
    parameter = json.loads(data)
    if len(parameter) == 3 or len(parameter) == 4:
        time_stamp = str(int(time.time()))
        parameter.append(time_stamp)
        executor_duplicate_project.submit(duplicate_main_project, parameter)        
        back = '已接收到project去重请求(%s)' % time_stamp
    else:
        back = '输入参数不合法'
    return back
def duplicate_main_project(parameter):
    if len(parameter) == 4:
        list_id_delete, list_id_error = market_batch_project.duplicate_batch(parameter[0],parameter[1],parameter[2],time_stamp=parameter[3])
    if len(parameter) == 5:
        list_id_delete, list_id_error = market_batch_project.duplicate_batch(parameter[0],parameter[1],parameter[2],body=parameter[3],time_stamp=parameter[4])
        
@app.route('/load_result',methods=['POST'])
def load_result():
    data = request.get_data()
    parameter = json.loads(data)
    flag = parameter[0]
    if flag == '去重':    
        with open('/home/analysis-project/market_log/duplicate_result.json','r') as load_f:
            result = json.load(load_f)
            if result['时间戳'] == parameter[1]:
                return str(result)
    elif flag == '打标':    
        with open('/home/analysis-project/market_log/label_result.json','r') as load_f:
            result = json.load(load_f)
            if result['时间戳'] == parameter[1]:
                return str(result)
    return '未找到结果'

@app.route('/duplicate_batch',methods=['POST'])
def duplicate_batch():
    data = request.get_data()
    parameter = json.loads(data)
    if len(parameter) == 3 or len(parameter) == 4:
        executor_duplicate.submit(duplicate_main, parameter)
        back = '已接收到全量去重请求'
    else:
        back = '输入参数不合法'
    return back
def duplicate_main(parameter):
    if len(parameter) == 3:
        market_main.duplicate_batch(parameter[0],parameter[1],parameter[2])
    elif len(parameter) == 4:
        market_main.duplicate_batch(parameter[0],parameter[1],parameter[2],parameter[3])

@app.route('/label_batch',methods=['POST'])
def label_batch():
    data = request.get_data()
    parameter = json.loads(data)
    if len(parameter) == 3:
        time_stamp = str(int(time.time()))
        parameter.append(time_stamp)
        executor_label.submit(label_main, parameter)
        back = '已接收到全量打标请求(%s)' % time_stamp
    elif len(parameter) == 4 or len(parameter) == 5:
        time_stamp = str(int(time.time()))
        parameter.append(time_stamp)
        executor_label.submit(label_main, parameter)
        back = '已接收到自定义打标请求(%s)' % time_stamp
    else:
        back = '输入参数不合法'
    return back
def label_main(parameter):
    if len(parameter) == 4:
        market_main.label_batch(parameter[0],parameter[1],parameter[2],time_stamp=parameter[3])
    elif len(parameter) == 5:
        market_main.label_batch(parameter[0],parameter[1],parameter[2],parameter[3],time_stamp=parameter[4])
    elif len(parameter) == 6:
        market_main.label_batch(parameter[0],parameter[1],parameter[2],parameter[3],parameter[4],time_stamp=parameter[5])
    
@app.route('/check_single',methods=['POST'])
def check_single():
    data = request.get_data()
    parameter = json.loads(data)
    if len(parameter) == 4:
        executor_single.submit(single_main, parameter)
        back = '已接收到单条入库请求'
    else:
        back = '输入参数不合法'
    return back
def single_main(parameter):
    market_main.check_single(parameter[0],parameter[1],parameter[2],parameter[3])

@app.route('/single_check_notice',methods=['POST'])
def single_check_notice():
    data = request.get_data()
    parameter = json.loads(data)
    result = market_single_notice.duplicate_single_only_main(parameter[0],parameter[1],parameter[2],parameter[3])
    return str(result)

'''
word与pdf解析
'''
@app.route('/word_pdf_parse',methods=['POST'])
def word_pdf_parse():
    data = request.get_data()
    parameter = json.loads(data)
    result = pdf_filepath.filepath_choose(parameter[0])
    return str(result)

if __name__ == '__main__':
  WSGIServer(('0.0.0.0', 8888), app).serve_forever()
  # WSGIServer(('0.0.0.0', 8887), app).serve_forever()
